﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.IO;
using DotPowerJob.Requests;
using Newtonsoft.Json;
using DotPowerJob.Responses;

namespace DotPowerJob
{
    public class PowerJobRestfulServiceHandler
    {
        private readonly ILogger _logger;
        private readonly JobDispatcher _jobDispatcher;
        public PowerJobRestfulServiceHandler(ILogger<PowerJobRestfulServiceHandler> logger, JobDispatcher jobDispatcher)
        {
            _logger = logger;
            _jobDispatcher = jobDispatcher;
        }

        public async Task HandlerAsync(HttpRequest request, HttpResponse response)
        {
            var path = request.Path.Value;
            var arrParts = path.Split('/');
            var method = arrParts[arrParts.Length - 1].ToLower();
            string result = string.Empty;
            try
            {
                string json = string.Empty;
                using (var stream = new StreamReader(request.Body))
                {
                    json = await stream.ReadToEndAsync();
                }
                json = json ?? string.Empty;
                switch (method)
                {
                    case "runjob":
                        result = this.RunJob(JsonConvert.DeserializeObject<ServerScheduleJobRequest>(json));
                        break;
                    case "stopinstance":
                        result = this.StopInstance(JsonConvert.DeserializeObject<ServerQueryInstanceStatusRequest>(json));
                        break;
                    //case "queryinstancestatus":
                    //    result = this.Queryinstancestatus(JsonConvert.DeserializeObject<ServerQueryInstanceStatusRequest>(json));
                    //    break;
                }
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, "响应出错" + ex.Message);
            }
            response.ContentType = "application/json;charset=utf-8";
            await response.WriteAsync(result);
        }

        /// <summary>
        /// 运行任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private string RunJob(ServerScheduleJobRequest request)
        {
            this._jobDispatcher.Execute(request);
            return "success";
        }

        /// <summary>
        /// 停止任务实例
        /// </summary>
        /// <returns></returns>
        private string StopInstance(ServerQueryInstanceStatusRequest request)
        {
            var result = this._jobDispatcher.TryRemoveInstanceTask(request.InstanceId);
            return result ? "success" : "failed";
        }

        /// <summary>
        /// 任务实例状态查询
        /// </summary>
        /// <returns></returns>
        private InstanceDetailResponse Queryinstancestatus(ServerQueryInstanceStatusRequest request)
        {
            return new InstanceDetailResponse() { };
        }
    }
}
